package com.jzqf.smart.utils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * map转换工具类
 * 2019/12/30 9:15
 *
 * @author LiuWeiHao
 */
public class ConvertMapHelper {


    /**
     * 将javabean转为map类型，然后返回一个map类型的值
     *
     * @param obj 对象
     * @return Map集合
     * @throws Exception 异常
     */
    public static Map<String, String> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        //支持父类属性
        Field[] fields = obj.getClass().getDeclaredFields();
        List<Field> list = new ArrayList<>(Arrays.asList(fields));
        Class<?> superClazz = obj.getClass().getSuperclass();
        if (superClazz != null) {
            Field[] superFields = superClazz.getDeclaredFields();
            list.addAll(Arrays.asList(superFields));
        }
        for (Field field : list) {
            field.setAccessible(true);
            if (null != field.get(obj)) {
                //过滤
                if (!field.getName().contains("shadow")) {
                    map.put(field.getName(), String.valueOf(field.get(obj)));
                }
            }
        }
        return map;
    }

    /**
     * 将javabean转为map类型，然后返回一个map类型的值,不支持父类属性
     *
     * @param obj 对象
     * @return Map集合
     * @throws Exception 异常
     */
    public static Map<String, String> objectSelefToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, String> map = new TreeMap<>();
        //不支持父类属性
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            //AccessibleTest类中的成员变量为private,故必须进行此操作
            field.setAccessible(true);
            field.getName();
            map.put("_" + toLowerStart(field.getName()), field.getName());
        }
        return map;
    }

    public static String toLowerStart(String value) {
        if (Character.isUpperCase(value.charAt(0))) {
            return (new StringBuilder()).append(Character.toLowerCase(value.charAt(0))).append(value.substring(1)).toString();
        } else {
            return value;
        }
    }
}
